from django.db import models
from django.conf import settings


class KnowledgeNode(models.Model):
    """知识节点"""
    NODE_TYPE_CHOICES = [
        ('concept', '概念'),
        ('skill', '技能'),
        ('topic', '主题'),
        ('course', '课程'),
    ]

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用户')
    name = models.CharField(max_length=100, verbose_name='节点名称')
    node_type = models.CharField(max_length=20, choices=NODE_TYPE_CHOICES, verbose_name='节点类型')
    description = models.TextField(null=True, blank=True, verbose_name='描述')
    difficulty_level = models.IntegerField(default=1, verbose_name='难度等级(1-5)')
    prerequisites = models.ManyToManyField('self', symmetrical=False, blank=True,
                                           related_name='dependents', verbose_name='前置知识')
    documents = models.ManyToManyField('knowledge.Document', blank=True, verbose_name='关联文档')
    mastery_level = models.IntegerField(default=0, verbose_name='掌握程度(0-100)')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'knowledge_node'
        verbose_name = '知识节点'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']
        unique_together = ['user', 'name']

    def __str__(self):
        return f'{self.user.username} - {self.name}'


class LearningPath(models.Model):
    """学习路径"""
    STATUS_CHOICES = [
        ('not_started', '未开始'),
        ('in_progress', '进行中'),
        ('completed', '已完成'),
        ('paused', '已暂停'),
    ]

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用户')
    title = models.CharField(max_length=200, verbose_name='路径标题')
    description = models.TextField(null=True, blank=True, verbose_name='描述')
    target_node = models.ForeignKey(KnowledgeNode, on_delete=models.CASCADE,
                                    related_name='target_paths', verbose_name='目标知识节点')
    nodes = models.ManyToManyField(KnowledgeNode, through='PathNode', verbose_name='包含的节点')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='not_started', verbose_name='状态')
    progress = models.IntegerField(default=0, verbose_name='进度(0-100)')
    estimated_hours = models.IntegerField(null=True, blank=True, verbose_name='预估学时')
    started_at = models.DateTimeField(null=True, blank=True, verbose_name='开始时间')
    completed_at = models.DateTimeField(null=True, blank=True, verbose_name='完成时间')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'learning_path'
        verbose_name = '学习路径'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return f'{self.user.username} - {self.title}'


class PathNode(models.Model):
    """学习路径中的节点"""
    STATUS_CHOICES = [
        ('locked', '锁定'),
        ('available', '可学习'),
        ('in_progress', '学习中'),
        ('completed', '已完成'),
    ]

    path = models.ForeignKey(LearningPath, on_delete=models.CASCADE, verbose_name='学习路径')
    node = models.ForeignKey(KnowledgeNode, on_delete=models.CASCADE, verbose_name='知识节点')
    order = models.IntegerField(verbose_name='顺序')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='locked', verbose_name='状态')
    progress = models.IntegerField(default=0, verbose_name='进度(0-100)')
    started_at = models.DateTimeField(null=True, blank=True, verbose_name='开始时间')
    completed_at = models.DateTimeField(null=True, blank=True, verbose_name='完成时间')

    class Meta:
        db_table = 'path_node'
        verbose_name = '路径节点'
        verbose_name_plural = verbose_name
        ordering = ['path', 'order']
        unique_together = ['path', 'node']

    def __str__(self):
        return f'{self.path.title} - {self.node.name} ({self.order})'


class StudyRecord(models.Model):
    """学习记录"""
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用户')
    node = models.ForeignKey(KnowledgeNode, on_delete=models.CASCADE, verbose_name='知识节点')
    duration_minutes = models.IntegerField(verbose_name='学习时长(分钟)')
    notes = models.TextField(null=True, blank=True, verbose_name='学习笔记')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'study_record'
        verbose_name = '学习记录'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return f'{self.user.username} - {self.node.name} - {self.duration_minutes}min'


class ReviewTask(models.Model):
    """复习任务"""
    STATUS_CHOICES = [
        ('pending', '待复习'),
        ('completed', '已完成'),
        ('skipped', '已跳过'),
    ]

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用户')
    node = models.ForeignKey(KnowledgeNode, on_delete=models.CASCADE, verbose_name='知识节点')
    scheduled_date = models.DateField(verbose_name='计划复习日期')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='状态')
    completed_at = models.DateTimeField(null=True, blank=True, verbose_name='完成时间')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'review_task'
        verbose_name = '复习任务'
        verbose_name_plural = verbose_name
        ordering = ['scheduled_date']
        indexes = [
            models.Index(fields=['user', 'scheduled_date', 'status']),
        ]

    def __str__(self):
        return f'{self.user.username} - {self.node.name} - {self.scheduled_date}'
